<?php
namespace admin\model;

use admin\model\Model;

class CommentModel extends Model{
    
    /**
     *  获取所有评论
     */
    public function getCommentAll($params = array('page' => 0,'limit' => 0)){
        $curr = ($params['page']-1)*$params['limit'];
        $sql = "SELECT comment.id,comment.user_name,comment.user_mail,comment.user_portrait,blog_info.title,comment.content,comment.praise_count,comment.is_top,comment.time,comment.state 
        FROM COMMENT,blog_info 
        WHERE comment.blog_id=blog_info.id  ";
        if(isset($params['content'])){
            $sql.=" AND comment.content LIKE :content ORDER BY comment.id ASC LIMIT {$curr},{$params['limit']} ";
            $data = $this->p_queryAll($sql,array('content'=>'%'.$params['content'].'%'));
        }else{
            $sql.=" ORDER BY comment.id ASC LIMIT {$curr},{$params['limit']} ";
            $data = $this->queryAll($sql);
        }
        return $this->filter($data);
    }
    /**
     * 数据过滤
     */
    public function filter($data){
        $len = count($data,COUNT_NORMAL);       //统计数组长度
        for($i=0;$i<$len;++$i){
            $data[$i]['time'] =  date("Y-m-d H:i",$data[$i]['time']);       //发表时间
            $data[$i]['is_top'] = $data[$i]['is_top']==='0'?'不置顶':'置顶'; 
            $data[$i]['state'] = $data[$i]['state']==='0'?'不可见':'可见'; 
        }
        return $data;
    }
    /**
     * 获取评论数量
     */
    public function getCommentCount($params){
        $sql = 'SELECT COUNT(*) AS count FROM comment';
        if(isset($params['content'])){
            $sql.=' WHERE comment.content LIKE :content';
            $data = $this->p_query($sql,array('content'=>'%'.$params['content'].'%'));
        }else{
            $data = $this->query($sql);
        }
        return $data;
    }
    /**
     * 更新表中部分字段 
     */
    public function updateComment($params){
        $sql = "UPDATE comment SET user_name=:user_name,content=:content,praise_count=:praise_count,is_top=:is_top,state=:state WHERE id=:id";  
        $this->p_execute($sql,$params);
        $num = $this->db->num;
        if($num == 1 ){
            $res['code'] = '1';
        }else{
            $res['code'] = '0';
        }
        return json_encode($res);
    }
    /**
     * 隐藏留言
     */
    public function hideComment($params){
        $sql = "UPDATE comment SET state = 0 WHERE id = :id";
        $this->p_execute($sql,$parmas);
        $data = [];
        $data['code'] = $this->db->num;
        return $data;
    }
    /**
     * 删除评论
     */
    public function delComment($parmas){
        $sql = 'DELETE FROM comment WHERE id=:id';
        $this->p_execute($sql,$parmas);
        $data = [];
        //判断删除入成功，设置返回数据
        if($this->db->num == 1){
            $data['code'] = '1';
        }else{
            $data['code'] = '0';
        }
        return $data;
    }
    
}